package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.GroupVo;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.GroupMemberAvatarAdapter;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.GroupChatSetView;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.util.ReadFinishCycTimeUtil;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.nic.view.util.JToast;
import com.nic.view.widget.GridSpacingItemDecoration;
import com.nic.view.widget.MyGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GroupChatSetActivity extends AppEventActivity<GroupChatSetView> implements GroupMemberAvatarAdapter.OnMemberClickListener {


    @BindView(R.id.gv_member)
    MyGridView gvMember;
    @BindView(R.id.tv_group_name)
    TextView tvGroupName;
    @BindView(R.id.tv_group_id)
    TextView tvGroupId;
    @BindView(R.id.ll_group_name)
    LinearLayout llGroupName;
    @BindView(R.id.ll_group_notice)
    LinearLayout llGroupNotice;
    @BindView(R.id.tv_group_notice)
    TextView tvGroupNotice;
    @BindView(R.id.tv_read_finish)
    TextView tvReadFinish;
    @BindView(R.id.sw_read_finish_clear)
    SwitchCompat swReadFinishClear;
    @BindView(R.id.cb_read_finish_clear)
    CheckBox cbReadFinishClear;
    @BindView(R.id.tv_read_finish_clear)
    TextView tvReadFinishClear;
    @BindView(R.id.ll_read_finish_clear)
    LinearLayout llReadFinishClear;
    @BindView(R.id.tv_delete_friend)
    TextView tvDeleteFriend;
    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;
    @BindView(R.id.ll_send_msg)
    LinearLayout llSendMsg;
    @BindView(R.id.tv_more)
    TextView tvMore;
    //    private GroupMemberAdapter adapter;
    private String targetId;
    private String targetName;
    private String targetType;
    private boolean isGroupOwner;
    private int clickGroupMemberPosition;
    private String mCurrentUserGroupMemberId;
    private GroupMemberAvatarAdapter avatarAdapter;
    private boolean isGotoSendMsg;
    private int pageSize = 35;
    private List<FriendTable> allList = new ArrayList<>();

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_group_chat_set;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setTitle("聊天信息");
        targetName = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_NAME);
        targetId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_ID);
        targetType = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_TYPE);
        isGotoSendMsg = getIntent().getBooleanExtra("Extra_CanGotoSendMsg", false);
        ReadFinishCycTimeUtil.getInstance().setReadFinishCycTime(this, Canstants.getGroupReadFinishKey(targetId, ChatApp.getInstance().getUserId()), tvReadFinishClear);
//        ReadFinishCycTimeUtil.getInstance().setReadFinishCycChangeListener(this, Canstants.isGroupReadFinishKey(targetId, ChatApp.getInstance().getUserId()), swReadFinishClear, llReadFinishClear);
        ReadFinishCycTimeUtil.getInstance().setReadFinishCycChangeListener(this, Canstants.isGroupReadFinishKey(targetId, ChatApp.getInstance().getUserId()), cbReadFinishClear, llReadFinishClear);
//        adapter = new GroupMemberAdapter();
//        adapter.setOnMemberClickListener(this);
//        gvMember.setAdapter(adapter);


        GridLayoutManager manage = new GridLayoutManager(this, 5);
        recyclerView.setLayoutManager(manage);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(5, getResources().getDimensionPixelOffset(R.dimen.dimen_4), false));
        initAdapter();
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<GroupTable>() {
            @Override
            public void onAction(GroupTable obj) {
                if (obj != null) {
                    tvGroupNotice.setText(obj.getAnnouncementContent());
                    tvGroupName.setText(obj.getGroupName());
                    tvGroupId.setText(obj.getGroupId());
                }
            }

            @Override
            public GroupTable onThreadAction() {
                GroupMemberTable query = GroupMemberTable.query(targetId, UserPreferences.getUserId());
                if (query != null)
                    mCurrentUserGroupMemberId = query.getGroupMemberId();
                return GroupTable.queryRowByGroupId(targetId);
            }
        });
        llSendMsg.setVisibility(isGotoSendMsg ? View.VISIBLE : View.GONE);
    }

    private void initAdapter() {
        avatarAdapter = new GroupMemberAvatarAdapter();
        avatarAdapter.setGroupId(targetId);
        avatarAdapter.setOnMemberClickListener(this);
        recyclerView.setAdapter(avatarAdapter);
    }


    @OnClick({R.id.tv_more, R.id.ll_group_name, R.id.ll_group_notice, R.id.ll_read_finish_clear, R.id.tv_delete_friend, R.id.ll_send_msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_more:

                if (allList.size() <= pageSize) {
                    avatarAdapter.addList(getSubList(allList, 0, allList.size()), isGroupOwner);
                } else {
                    avatarAdapter.addList(getSubList(allList, 0, pageSize), isGroupOwner);
                }
                if (allList.isEmpty()) {
                    tvMore.setVisibility(View.GONE);
                }
                break;
            case R.id.ll_group_name:
                if (isGroupOwner) {
                    ModifyRemarkActivity.jumpToModifyGroupName(this, targetId);
                }
                break;
            case R.id.ll_group_notice:
                if (isGroupOwner) {
                    GroupNoticeSetActivity.jumpTo(this, targetId);
                }
                break;
            case R.id.ll_read_finish_clear:
                ReadFinishCycTimeUtil.getInstance().showPop(this, Canstants.getGroupReadFinishKey(targetId, ChatApp.getInstance().getUserId()), tvReadFinishClear);
                break;
            case R.id.tv_delete_friend:
                if (isGroupOwner) {
                    new RectButtonHintDialog(this)
                            .setTitle("确认退出")
                            .setContent("您是群主，退出后将解散此群组，确定要退出吗？")
                            .setLeftSubmit("取消", null)
                            .setRightSubmit("确认", v -> obtainView().doDissolveGroup(targetId, targetName, mCurrentUserGroupMemberId))
                            .show();
                } else {
                    new RectButtonHintDialog(this)
                            .setTitle("确认退出")
                            .setContent("确定要退出此群组吗？")
                            .setLeftSubmit("取消", null)
                            .setRightSubmit("确认", v -> obtainView().doExitGroup(targetId, targetName, mCurrentUserGroupMemberId))
                            .show();
                }
                break;
            case R.id.ll_send_msg:
                GroupChatActivity.jumpTo(this, Canstants.GROUP_CHAT, targetName, targetId, targetType);
                finish();
                break;
        }
    }

    public static <T> List<T> getSubList(List<T> list, int fromIndex, int toIndex) {
        //list.stream().limit(toIndex);
        if (toIndex > list.size()) {
        }
        List listClone = list;
        List sub = listClone.subList(fromIndex, toIndex);
        List two = new ArrayList(sub);
        sub.clear(); // since sub is backed by one, this removes all sub-list items from one
        return two;
    }

    public void setData() {
        ObserverThread.create().onNextThread2(new ObserverThread.OnListActionListener<FriendTable>() {
            @Override
            public void onAction(List<FriendTable> list) {
//                adapter.setList(list);
                if (!list.isEmpty()) {
                    tvMore.setVisibility(View.VISIBLE);
                    allList.clear();
                    allList.addAll(list);
                    if (allList.size() <= pageSize) {
                        avatarAdapter.setList(allList, isGroupOwner);
                        tvMore.setVisibility(View.GONE);
                    } else {
                        avatarAdapter.addList(getSubList(allList, 0, pageSize), isGroupOwner);
                    }
                }
            }

            @Override
            public List<FriendTable> onThreadAction() {
                GroupMemberTable i = GroupMemberTable.query(targetId, UserPreferences.getUserId());
                if (i != null)
                    mCurrentUserGroupMemberId = i.getGroupMemberId();
                List<GroupMemberTable> query = GroupMemberTable.query(targetId);
                List<FriendTable> set = new ArrayList<>();
                for (GroupMemberTable groupMemberTable : query) {
                    FriendTable tableByFriendUserId = FriendTable.getTableByFriendUserId(groupMemberTable.getGroupMemberUserId());
                    if (null != tableByFriendUserId) {
                        FriendTable f = new FriendTable();
                        f.setFriendUserId(tableByFriendUserId.getFriendUserId());
                        f.setFriendNickname(tableByFriendUserId.getFriendNickname());
                        f.setFriendAvatar(tableByFriendUserId.getFriendAvatar());
                        f.setFriendAvatarId(tableByFriendUserId.getFriendAvatarId());
                        f.setFriendAvatarPath(tableByFriendUserId.getFriendAvatarPath());
                        f.setFriendAlias(tableByFriendUserId.getFriendAlias());
                        f.setUserType(tableByFriendUserId.getUserType());
                        f.setLoginUserId(UserPreferences.getUserId());
                        if (groupMemberTable.getGroupMemberType() == 1) {
                            isGroupOwner = tableByFriendUserId.getFriendUserId().equals(UserPreferences.getUserId());
                        }
                        set.add(f);
                    } else if (groupMemberTable.getGroupMemberUserId().equals(ChatApp.getInstance().getUserId())) {
                        UserTableBean u = ChatApp.getInstance().get();
                        groupMemberTable.setGroupMemberAvatar(groupMemberTable.getGroupMemberAvatar());
                        groupMemberTable.setGroupMemberAvatarId(u.getAvatarId());
                        groupMemberTable.setGroupMemberAvatarPath(u.getAvatarPath());
                        GroupMemberTable.update(groupMemberTable);
                        FriendTable f = new FriendTable();
                        f.setFriendUserId(UserPreferences.getUserId());
                        f.setFriendNickname(u.getNickname());
                        f.setFriendAvatar(groupMemberTable.getGroupMemberAvatar());
                        f.setFriendAvatarPath(u.getAvatarPath());
                        f.setFriendAlias(u.getNickname());
                        f.setUserType(u.getUserType());
                        f.setLoginUserId(UserPreferences.getUserId());
                        if (groupMemberTable.getGroupMemberType() == 1) {
                            isGroupOwner = f.getFriendUserId().equals(UserPreferences.getUserId());
                        }
                        set.add(f);
                    } else {
                        FriendTable f = new FriendTable();
                        f.setFriendUserId(groupMemberTable.getGroupMemberUserId());
                        f.setFriendNickname(groupMemberTable.getGroupMemberName());
                        f.setFriendAvatar(groupMemberTable.getGroupMemberAvatar());
                        f.setFriendAvatarId(groupMemberTable.getGroupMemberAvatarId());
                        f.setFriendAvatarPath(groupMemberTable.getGroupMemberAvatarPath());
                        f.setFriendAlias(groupMemberTable.getGroupMemberAlias());
                        f.setUserType(groupMemberTable.getUserType());
                        f.setLoginUserId(UserPreferences.getUserId());
                        if (groupMemberTable.getGroupMemberType() == 1) {
                            isGroupOwner = f.getFriendUserId().equals(UserPreferences.getUserId());
                        }
                        set.add(f);
                    }
                }
                return set;
            }
        });
    }

//    public void setData1() {
//        ObserverThread.create().onNextThread2(new ObserverThread.OnListActionListener<GroupMemberTable>() {
//            @Override
//            public void onAction(List<GroupMemberTable> list) {
//                avatarAdapter.setList(list);
//                recyclerView.postDelayed(() -> obtainView().doGetGroupMemberList(targetId), 300);
//            }
//
//            @Override
//            public List<GroupMemberTable> onThreadAction() {
//                GroupMemberTable i = GroupMemberTable.query(targetId, UserPreferences.getUserId());
//                if (i != null)
//                    mCurrentUserGroupMemberId = i.getGroupMemberId();
//                List<GroupMemberTable> query = GroupMemberTable.query(targetId);
//                for (GroupMemberTable groupMemberTable : query) {
//                    if (groupMemberTable.getGroupMemberType() == GroupMemberTable.OWNER) {//群主
//                        isGroupOwner = groupMemberTable.getGroupMemberUserId().equals(UserPreferences.getUserId());
//                    }
//                }
//                return query;
//            }
//        });
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Canstants.MODIFT_TARGETNAME_CODE == requestCode && Canstants.MODIFT_TARGETNAME_CODE == resultCode) {
            String remark = data.getStringExtra(Canstants.KEY_REMARK);
            avatarAdapter.modifyGroupMamberAlias(clickGroupMemberPosition, remark);
            return;
        }
        if (Canstants.KEY_GROUP_NOTICE_RESULT == requestCode && Canstants.KEY_GROUP_NOTICE_RESULT == resultCode) {
            String remark = data.getStringExtra(Canstants.KEY_GROUP_NOTICE);
            tvGroupNotice.setText(remark);
            return;
        }
        if (Canstants.KEY_GROUP_INVITE_RESULT == requestCode && Canstants.KEY_GROUP_INVITE_RESULT == resultCode) {
            setData();
            return;
        }
        if (Canstants.KEY_REMARK_RESULT == requestCode && Canstants.KEY_REMARK_RESULT == resultCode) {
            String remark = data.getStringExtra(Canstants.KEY_REMARK);
            tvGroupName.setText(remark);
            MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.GROUP_NAME_CHANGED);
            event.setData(remark);
            EventBus.getDefault().post(event);
        }
    }


    @Override
    public void onClick(int position, View v, int footState, FriendTable item) {
        if (Canstants.MEMBER_STATE_ADD == footState) {
//            if (adapter.getData().isEmpty()) {
//                return;
//            }
            InviteFriendActivity.jumpToInvite(this, targetId);
        } else if (Canstants.MEMBER_STATE_REMOVE == footState) {
            if (!isGroupOwner || avatarAdapter.getList().isEmpty()) {
                return;
            }
            InviteFriendActivity.jumpToDelete(this, targetId, targetName, mCurrentUserGroupMemberId);
        } else {
//            if (!item.getFriendUserId().equals(UserPreferences.getUserId())) {
//                clickGroupMemberPosition = position;
//                FriendInfoActivity.jumpTo(GroupChatSetActivity.this, targetId, item.getFriendNickname(), item.getFriendUserId());
//            }
            if (item.getFriendUserId().equals(UserPreferences.getUserId())) {
                v.getContext().startActivity(new Intent(v.getContext(), PersonalActivity.class));
            } else if (FriendTable.isExistFriendById(item.getFriendUserId())) {
                clickGroupMemberPosition = position;
                String userType = IMSUtils.userTypeAnalysis(item.getFriendUserId());
                FriendInfoActivity.jumpTo(GroupChatSetActivity.this, IMSContacts.UserType.REGISTERED_USER.equals(userType) ? Canstants.KEY_REGISTER : Canstants.KEY_VISITOR, item.getFriendNickname(), item.getFriendUserId(), userType);
            } else {
                clickGroupMemberPosition = position;
                FriendInfoActivity.jumpTo(GroupChatSetActivity.this, targetId, item.getFriendNickname(), item.getFriendUserId());
//                SearchBean search = new SearchBean();
//                if (IMSContacts.UserType.REGISTERED_USER.equals(item.getUserType())) {
//                    search.setUserId(item.getFriendUserId());
//                } else {
//                    search.setTouristId(item.getFriendUserId());
//                }
//                search.setAvatars(item.getFriendAvatar());
//                search.setName(item.getFriendNickname());
//                SearchResultActivity.jumpTo((Activity) v.getContext(), Canstants.KEY_SEARCH_FRIEND, search);
            }
        }
    }

    public static void jumpTo(Activity context, String targetName, String targetId, String targetType) {
        Intent intent = new Intent(context, GroupChatSetActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_NAME, targetName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, targetType);
        context.startActivityForResult(intent, Canstants.REQUEST_CODE_BACK);
        ChatApp.getInstance().inActivityAnim(context);
    }

    public static void jumpToSend(Activity context, String targetName, String targetId, String targetType) {
        Intent intent = new Intent(context, GroupChatSetActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_NAME, targetName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, targetType);
        intent.putExtra("Extra_CanGotoSendMsg", true);
        context.startActivityForResult(intent, Canstants.REQUEST_CODE_BACK);
    }

    @Override
    protected int setupEventBusRegSite() {
        return EVENT_REG_ON_CREATE;
    }

    @Override
    protected void afterOnCreateRegisterEventBus() {
        obtainView().doGetGroupMemberList(targetId);
    }

    @Override
    protected GroupChatSetView bindNettyMessageView() {
        return new GroupChatSetView(new GroupChatSetView.GroupChatSetCallback() {
            @Override
            public void onGetGroupMemberListCallback(int code, String msg, GroupVo data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    tvGroupId.setText(String.valueOf(data.getGroupId()));
                    tvGroupName.setText(data.getName());
                    tvGroupNotice.setText(data.getAnnouncement());
                    MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.GROUP_NAME_CHANGED);
                    event.setData(data.getName());
                    EventBus.getDefault().post(event);
                }
                setData();
            }

            @Override
            public void onExitToGroupCallback(int code, String msg) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                        @Override
                        public void onAction(Object obj) {
                            setResult(Canstants.REQUEST_CODE_BACK);
                            finish();
                        }

                        @Override
                        public Object onThreadAction() {
                            GroupTable.deleteByGroupId(targetId);
                            GroupMemberTable.deleteByGroupId(targetId);
                            ChatTableBean.deleteByGroupId(targetId);
                            ChatContentTable.deleteById(targetId, Canstants.GROUP_CHAT);
                            return null;
                        }
                    });
                } else {
                    if (TextUtils.isEmpty(msg)) msg = "退群失败";
                    JToast.showShort(GroupChatSetActivity.this, msg);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUiRefreshNotification(MessageEvent me) {
        if (me == null || me.event() != EventConstants.Event.UI_REFRESH_NOTIFICATION)
            return;
        if (me.action() == EventConstants.Action.DELETE_GROUP ||
                me.action() == EventConstants.Action.EXIT_GROUP) {
            if (!TextUtils.isEmpty(me.data())) {
                String[] split = me.data().split("_");
                if (split.length > 1) {
                    if (split[1].contains(UserPreferences.getUserId())) {
                        if (me.action() == EventConstants.Action.DELETE_GROUP) {
                            JToast.showShort(this, me.action() == EventConstants.Action.DELETE_GROUP ? "你被移出了群聊" : "你退出了群聊");
                            finish();
                        }
                    } else {
                        removeByMemberUserId(split[1]);
                    }
                }
            }
        } else if (me.action() == EventConstants.Action.DISSOLVE_GROUP) {
            if (!TextUtils.isEmpty(me.data()) && me.data().equals(targetId)) {
                JToast.showShort(this, "该群被解散了");
                finish();
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initAdapter();
        setData();
    }

    public void removeByMemberUserId(String memberId) {
        if (TextUtils.isEmpty(memberId))
            return;
        avatarAdapter.removeByMemberUserId(memberId);
//        for (int i = 0; i < allList.size(); i++) {
//            FriendTable table = allList.get(i);
//            if (table != null && memberId.contains(table.getFriendUserId())) {
//                allList.remove(i--);
//            }
//        }
    }
}
